package com.toman.ui.work.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ShiftAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.ShiftEntity;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.LoadingEmptyActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

public class ShiftEmptyActivity extends LoadingEmptyActivity implements ShiftAdapter.ActionClickListener {

    @BindView(R.id.lv)
    ListView lv;
    ShiftAdapter adapter;
    List<ShiftEntity> list = new ArrayList<ShiftEntity>();
    PopupWindow popupWindow;
    String conttentTime;
    String conttentTime2;
    int HourOfDay;
    int Minute;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    private RadioGroup mGroup;
    int an;
    int HourOfDay1;
    int Minute1;
    TimePicker id_add_timePicker1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shift);
        ButterKnife.bind(this);
        initToolBar("班次信息");
        initView();
initLoad(1);
    }

    @Override
    protected Activity getContent() {
        return this;
    }

    @Override
    public void load() {
        if (!PermissonUtils.contains(this, BaseEnum.SHIFT.has(PermEnum.ADD))){
            ToastUtil.makeText(this,"没有权限，请联系管理员");
        }
        else{ add();}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_add, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_add);
        if (!PermissonUtils.contains(this, BaseEnum.SHIFT.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
                        add();
                        break;
                }
                return false;
            }
        });
        return true;
    }

    private void add() {
        Bundle bundle = new Bundle();
        bundle.putString("type", "1");
        bundle.putString("d_id", getIntent().getStringExtra("id"));
        bundle.putString("dep_name", getIntent().getStringExtra("dep_name"));
        IntentUtils.startActivity(ShiftEmptyActivity.this, ShiftAddActivity.class, bundle);
    }

    private void addDialog() {
    }

    private void editDialog(ShiftEntity bean) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        customer(1, 1, "");

    }

    private void initView() {
        adapter = new ShiftAdapter(this);

        lv.setAdapter(adapter);
        adapter.setActionClickListener(this);

    }


    @Override
    public void onEditClick(ShiftEntity bean) {
//        ToastUtil.makeText(getApplicationContext(),"编辑");
        Bundle bundle = new Bundle();
        bundle.putString("type", "2");
        bundle.putString("d_id", getIntent().getStringExtra("id"));
        bundle.putString("id", bean.getId() + "");
        bundle.putString("end_time", bean.getEndTime());
        bundle.putString("start_time", bean.getStartTime());
        bundle.putString("name", bean.getShiftName());
        bundle.putString("shiftNum", bean.getShiftNum());
        bundle.putString("dep_id", bean.getDepartmentId());
        bundle.putString("dep_name", bean.getDepartmentName());
        if (bean.getIsToday()==null){
            bundle.putString("isToday", "0");
        }
else {
            bundle.putString("isToday", bean.getIsToday());
        }
        bundle.putString("deviceCheckStartTime", bean.getDeviceCheckStartTime());
        bundle.putString("deviceCheckEndTime", bean.getDeviceCheckEndTime());
        IntentUtils.startActivity(ShiftEmptyActivity.this, ShiftAddActivity.class, bundle);
    }

    @Override
    public void onDelClick(ShiftEntity bean) {
        deleteDialog(bean);
    }

    public void deleteDialog(final ShiftEntity bean) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确定要删除班次？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        delete(bean);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    private void delete(ShiftEntity bean) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.shift_delete_post+bean.getId())
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "删除班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            customer(1, 1, "");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    public void customer(Integer page, final Integer type, String search) {


        OkHttpUtils
                .get(NewBaseUrl.shift_list_get)
//                .params("departmentIdList",getIntent().getStringExtra("id"))
                .params("companyId", companyId)


                .params("token", token)
                .params("key", search)
                .params("limit", "100")
                .params("page", page.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "班次列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
//                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            List<ShiftEntity> jsonArray = new ArrayList<ShiftEntity>(JSONArray.parseArray(Jpage.getString("list"), ShiftEntity.class));
//                                ShiftEntity entity = new ShiftEntity(jsonArray.getJSONObject(i).getLong("id"), jsonArray.getJSONObject(i).getString("shiftName"), jsonArray.getJSONObject(i).getString("startTime"), jsonArray.getJSONObject(i).getString("endTime"),jsonArray.getJSONObject(i).getString("shiftNum"));
//                                ItemListBean bean = new ItemListBean( jsonArray.getJSONObject(i).getString("companyName"),jsonArray.getJSONObject(i).getString("id"));

                                list.addAll(jsonArray);

                            adapter.refreshData(list);
                        isEmpty(list,mMangeNodata);
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


}
